import type { ProColumns } from '@/components/Pro/';
import { ProTable } from '@/components/Pro/';
import { auditControllerImplListAudit } from '@/services/ess/audit';
import { stationAreaControllerImplListStationArea } from '@/services/ess/stationArea';
import { useIntl } from '@umijs/max';
import { message } from 'antd';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import { Link, useModel } from 'umi';
const stationAreaId = -1;

const TableList: React.FC = () => {
  const { isArea } = useModel('@@initialState')?.initialState || {};
  const intl = useIntl();
  const [stationAndAreaList, setStationAndAreaList] = useState([]);

  useEffect(() => {
    const fetchStationAreas = async () => {
      try {
        const response = await stationAreaControllerImplListStationArea();
        if (response.success && response.data) {
          const areas = response.data.map((area) => ({
            label: area.areaName,
            value: area.id,
          }));
          console.log('areas---', areas);
          setStationAndAreaList(areas as any); // Type assertion to fix type error
        }
      } catch (error) {
        console.error('Failed to fetch station areas:', error);
        message.error('获取分区列表失败');
      }
    };
    fetchStationAreas();
  }, []);
  const columns: ProColumns<API.auditControllerImplListAuditParams>[] = [
    {
      title: intl.formatMessage({
        id: 'global.s/N',
      }),
      dataIndex: 'pageIndex',
      valueType: 'index',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'strategyAction.management.operationTime',
      }),
      dataIndex: 'createdTime',
      valueType: 'dateTimeRange',
      render: (_, record) =>
        record.createdTime ? moment(record.createdTime).format('YYYY-MM-DD HH:mm:ss') : '--',
      width: 160,
      search: {
        transform: (value) => {
          return {
            from: value?.[0],
            until: value?.[1],
          };
        },
      },
    },
    {
      title: intl.formatMessage({
        id: 'strategyAction.management.operationHistory',
      }),
      dataIndex: 'operation',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'global.area',
      }),
      dataIndex: 'areaId',
      width: 100,
      order: 200,
      valueType: 'select',
      fieldProps: {
        options: stationAndAreaList,
        fieldNames: {
          label: 'label',
          value: 'value',
        },
      },
      search: {
        transform: (value) => ({
          areaId: value === stationAreaId ? null : value,
        }),
      },
      hideInTable: !isArea,
      hideInSearch: !isArea,
      render: (_, record) => {
        // Find the area name from the stationAndAreaList based on areaId
        const area = stationAndAreaList.find((a) => a.value === record.areaId);
        return area ? area.label : '整站';
      },
    },
    {
      title: intl.formatMessage({
        id: 'strategyAction.management.sendStatus',
      }),
      dataIndex: 'result',
      valueEnum: {
        1: {
          text: intl.formatMessage({
            id: 'global.successful',
          }),
        },
        0: {
          text: intl.formatMessage({
            id: 'global.failed',
          }),
        },
      },
      order: 100,
    },
    {
      title: intl.formatMessage({
        id: 'strategyAction.management.operator',
      }),
      dataIndex: 'userName',
      order: 1,
      fieldProps: {
        placeholder: intl.formatMessage({
          id: 'strategyControl.temporalStrategy.pleaseEnterAccountKeywords',
        }),
      },
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.operation' }),
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        // 获取区域名称
        const area = stationAndAreaList.find((a) => a.value === record.areaId);
        const areaName = area ? area.label : '整站';

        // 构建详情页面URL参数
        const params = new URLSearchParams({
          reqParam: record.reqParam || '',
          downTime: record.createdTime
            ? moment(record.createdTime).format('YYYY-MM-DD HH:mm:ss')
            : '--',
          history: record.operation || '',
          areaName: areaName,
          downStatus: record.result?.toString() || '0',
          downUser: record.userName || '',
        });

        return [
          <Link to={`/strategy/peakArbitrage/detail?${params.toString()}`} key="detail">
            {intl.formatMessage({
              id: 'strategyControl.temporalStrategy.detail',
            })}
          </Link>,
        ];
      },
    },
  ];
  return (
    <div>
      <ProTable
        cardProps={false}
        rowKey="id"
        request={async (params) => {
          const { areaId, ...restParams } = params;

          const response = await auditControllerImplListAudit(
            {
              ...restParams,
              current: params.current?.toString(),
              pageSize: params.pageSize?.toString(),
            },
            {
              headers: {
                'Station-Area': areaId ? String(areaId) : null,
              },
            },
          );

          return {
            data:
              response.data?.records?.map((record) => ({
                ...record,
                result: record.result?.toString(),
              })) || [],
            success: response.success,
            total: response.data?.total || 0,
          };
        }}
        columns={columns}
      />
    </div>
  );
};
export default TableList;
